import axios from 'axios';
import qs from 'qs';
import {MessageBox, Message} from 'element-ui';
import store from '@/store';
import router from '@/router';
import {getToken, getUserInfo} from '@/utils/auth';
import {getOnceTokenFn} from '@/api/getOnceToken';
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 100000 // request timeout
});

// request interceptor
service.interceptors.request.use(
    async config => {
        if (getToken()) {
            config.headers['token'] = getToken();
        }
        let copyData = config.data ? JSON.parse(JSON.stringify(config.data)) : {}
        if (getToken() && store.getters.userInfo) {
            const userInfo = store.getters.userInfo;
            // 请求参数控制
            if('type' in config && config.type == 'form-data/json'){
                // 列表单独处理 page、pageSize 用params传，其他参数用json
                config.params = {
                    page: copyData.page,
                    pageSize: copyData.pageSize
                }
                config.headers['Content-Type'] = 'application/json';
                delete copyData.page
                delete copyData.pageSize
                config.data = (copyData)
            } else {
                if ('params' in config) {
                    // 不处理
                } else if ('query' in config) {
                    config.headers['Content-Type'] = 'application/json';
                    config.data = (config.query);
                } else {
                    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                    config.data = qs.stringify(config.data);
                }
            }
        } else {
            // 请求参数控制
            if (!config.params) {
                if('type' in config && config.type == 'form-data/json'){
                    // 列表单独处理 page、pageSize 用params传，其他参数用json
                    config.params = {
                        page: copyData.page,
                        pageSize: copyData.pageSize
                    }
                    config.headers['Content-Type'] = 'application/json';
                    delete copyData.page
                    delete copyData.pageSize
                    config.data = (copyData)
                } else {
                    if (typeof config.data === 'undefined') {
                        config.data = {};
                    }
                    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                    if (config.data) {
                        config.data = qs.stringify(config.data);
                    }
                }
            }
        }

        return config;
    },
    error => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data;
        // if the custom code is not 20, it is judged as an error.
        if (res.code !== 1) {
            // 50008: Illegal token 非法token; 50012: Other clients logged in 其他登录; 50014: Token expired 登录过期;
            if (res.code === 50008) {
                // 刷新或重新操作
                Message({
                    message: res.message || '非法Token值，请您重新操作或刷新页面',
                    type: 'error',
                    duration: 5 * 1000
                });
                return new Error('非法Token值，请你重新操作或刷新页面');
            } else if (res.code === 50012 || res.code === 50014) {
                // 重新登录
                MessageBox.confirm('您的登录已过期，您可以取消停留在此页面，或重新登录', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        // 跳转登录页，无重定向，多端登录在permission中处理
                        router.push('/');
                    });
                }).catch(async () => {

                });
            }
            return Promise.reject(new Error(res.message || 'Error'));
            // return new Error(res.message || 'Error')
        } else {
            return res;
        }
    },
    error => {
        console.log('err' + error); // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        });
        // return Promise.reject(error)
        return new Error('Error');
    }
);

export default service;
